package com.example.casper.Experiment2024;


import static androidx.core.content.ContextCompat.getSystemService;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.casper.Experiment2024.data.BookItem;
import com.example.casper.Experiment2024.data.DataBank;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
//import com.example.casper.Experiment2024.data.Item;

import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory;
import com.tencent.tencentmap.mapsdk.maps.TencentMap;
import com.tencent.tencentmap.mapsdk.maps.TextureMapView;
import com.tencent.tencentmap.mapsdk.maps.model.BitmapDescriptorFactory;
import com.tencent.tencentmap.mapsdk.maps.model.LatLng;
import com.tencent.tencentmap.mapsdk.maps.model.Marker;
import com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ShoppingListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShoppingListFragment extends Fragment {

    public ShoppingListFragment() {
        // Required empty public constructor
    }

    private Context context;
    public void companyInfo(Context context){
        this.context = context;
    }

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    private double la;
    private double lo;
    private byte[] byte_bit;
    private ArrayList<BookItem> items;
    private ActivityResultLauncher<Intent> launcherAdd;
    private ActivityResultLauncher<Intent> launcherUpdate;
    private ShopItemAdapter shopItemAdapter;
    private FusedLocationProviderClient fusedLocationClient;
    private locationViewModel viewModel;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment ShoppingListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShoppingListFragment newInstance() {
        ShoppingListFragment fragment = new ShoppingListFragment();
        Bundle arg = new Bundle();
        fragment.setArguments(arg);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootViewer = inflater.inflate(R.layout.fragment_shopping_list, container, false);

        RecyclerView mainRecyclerView = rootViewer.findViewById(R.id.recyclerview_items);
        mainRecyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
        DataBank databank=new DataBank(this.getContext());
        viewModel = new ViewModelProvider(requireActivity()).get(locationViewModel.class);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(getActivity());
        items= databank.readItems();

        // 检查权限并获取位置
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            startLocationUpdates();
        }

        Button deliver_button = rootViewer.findViewById(R.id.deliver_button);
        deliver_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理按钮点击事件
                int len =shopItemAdapter.getItemCount();
                double[] latitude_tmp=new double[len];
                double[] longitude_tmp=new double[len];
                shopItemAdapter.set_lalo(latitude_tmp,longitude_tmp,len);
                viewModel.set_la(latitude_tmp);
                viewModel.set_lo(longitude_tmp);
            }
        });

        FloatingActionButton add_button = rootViewer.findViewById(R.id.floatingActionButton_1826);
        add_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在这里处理按钮点击事件
                Intent intentAdd = new Intent(getActivity(), BookItemDetailActivity.class);
                intentAdd.putExtra("position", 0);
                launcherAdd.launch(intentAdd);
            }
        });

        shopItemAdapter = new ShopItemAdapter(items);
        mainRecyclerView.setAdapter(shopItemAdapter);

        registerForContextMenu(mainRecyclerView);
        return rootViewer;
    }

    public void saveImageToDatabase(Bitmap bitmap) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); // 可以选择JPEG格式
        byte_bit = byteArrayOutputStream.toByteArray();

        // 关闭 ByteArrayOutputStream
        byteArrayOutputStream.close();
        // 这里可以将byteArray保存到SQLite数据库中
    }

    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(1000); // 设置更新间隔
        locationRequest.setFastestInterval(5000); // 设置最快更新时间
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // 高精度

        // 注册位置更新
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
    }

    private LocationCallback locationCallback = new LocationCallback() {
        @Override

        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                if (location != null) {
                    la = location.getLatitude();
                    lo = location.getLongitude();
                    // 使用经纬度
                    Log.d("Location Update", "Latitude: " + la + ", Longitude: " + lo);
                }
            }
        }
    };

    @SuppressLint("MissingPermission")
    private void getLastLocation() {
        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(getActivity(), location -> {
                    if (location != null) {
                        la = location.getLatitude();
                        lo = location.getLongitude();
                        // 使用经纬度
                        Log.d("Location", "Latitude: " + la + ", Longitude: " + lo);
                    }
                });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startLocationUpdates();
            } else {
                // 权限被拒绝，处理相应逻辑
                Log.e("Location", "Permission denied");
            }
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem itemMenu ) {
        switch (itemMenu.getItemId()) {
            case 0:
                Intent intentUpdate = new Intent(ShoppingListFragment.this.getContext(), BookItemDetailActivity.class);
                intentUpdate.putExtra("position",itemMenu.getOrder());
                BookItem itemObject= items.get(itemMenu.getOrder());
                intentUpdate.putExtra("item_name", itemObject.getTitle());
                intentUpdate.putExtra("item_data", itemObject.getContext_daka());
                launcherUpdate.launch(intentUpdate);
                break;
            case 1:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getContext());
                builder.setTitle(R.string.confirmation)
                        .setMessage(R.string.are_you_sure_you_want_to_delete_the_item)
                        .setPositiveButton(R.string.yes, (dialog, id) -> {
                            items.remove(itemMenu.getOrder());
                            shopItemAdapter.notifyItemRemoved(itemMenu.getOrder());
                            DataBank databank=new DataBank(ShoppingListFragment.this.getContext());
                            databank.saveItems(items);
                        })
                        .setNegativeButton(R.string.no, (dialog, id) -> {
                            // 用户取消删除
                            dialog.dismiss();
                        });
                // 创建并显示对话框
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            default:
                return super.onContextItemSelected(itemMenu);
        }
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        launcherAdd = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String itemName=data.getStringExtra("item_name");
                        String item_data=data.getStringExtra("item_data");
                        String item_uri_str=data.getStringExtra("uri");
                        int position = data.getIntExtra("position",0);

                        Uri uri_tmp=Uri.parse(item_uri_str);
                        ContentResolver contentResolver = requireActivity().getContentResolver();
                        Bitmap bitmap0 = null;
                        try {
                            bitmap0 = MediaStore.Images.Media.getBitmap(contentResolver, uri_tmp);
                            saveImageToDatabase(bitmap0);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
//                        la=data.getDoubleExtra("la",1.1);
//                        lo=data.getDoubleExtra("lo",1.1);
//                        Uri uri_tmp0=Uri.parse(item_uri_str);

                        BookItem niu=new BookItem(itemName, item_data,byte_bit);
                        niu.set_position(la,lo);
                        items.add(position,niu);
                        shopItemAdapter.notifyItemInserted(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveItems(items);
                    }
                });
        launcherUpdate = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent data = result.getData();
                        assert data != null;
                        String itemName = data.getStringExtra("item_name");
                        String itemData = data.getStringExtra("item_data");
                        String item_uri_str=data.getStringExtra("uri");
                        int position = data.getIntExtra("position", 0);

                        Uri uri_tmp=Uri.parse(item_uri_str);
                        ContentResolver contentResolver = requireActivity().getContentResolver();
                        Bitmap bitmap0 = null;
                        try {
                            bitmap0 = MediaStore.Images.Media.getBitmap(contentResolver, uri_tmp);
                            saveImageToDatabase(bitmap0);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }

                        BookItem item = items.get(position);
                        item.setTitle(itemName);
                        item.setContext_daka(itemData);
                        item.setUri_str(item_uri_str);
                        item.setByte(byte_bit);
                        shopItemAdapter.notifyItemChanged(position);
                        DataBank databank=new DataBank(this.getContext());
                        databank.saveItems(items);
                    }
                });


    }

    private class ShopItemAdapter extends RecyclerView.Adapter {
        private final List<BookItem> items;

        public ShopItemAdapter(List<BookItem> items) {
            this.items=items;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.recycle_1826, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            MyViewHolder myViewHolder= (MyViewHolder) holder;
            Bitmap bitmap0 = null;
            try {
                // 将 byte 数组解码为 Bitmap
                bitmap0 = BitmapFactory.decodeByteArray(items.get(position).get_byte(), 0, items.get(position).get_byte().length);
                Log.d("Fuck", "cnm");
            } catch (Exception e) {
                e.printStackTrace();
            }

            myViewHolder.getTextViewName().setText(items.get(position).getTitle());
            myViewHolder.getTextViewData().setText(items.get(position).getContext_daka());
            myViewHolder.getTextViewla().setText(Double.toString(items.get(position).get_la()));
            myViewHolder.getTextViewlo().setText(Double.toString(items.get(position).get_lo()));
            myViewHolder.getImageViewPicture().setImageBitmap(bitmap0);
//            myViewHolder.getImageViewPicture().setImageResource(items.get(position).getResourceId());
        }


        public void set_lalo(double[] la,double[] lo,int len){
            for (int i = 0; i < len; i++) {
                la[i]=items.get(i).get_la();
                lo[i]=items.get(i).get_lo();
            }
        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        private class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
            public ImageView getImageViewPicture() {
                return imageViewPicture;
            }

            public TextView getTextViewName() {
                return textViewName;
            }

            public TextView getTextViewData() {
                return textViewData;
            }

            public TextView getTextViewla() {
                return textViewla;
            }

            public TextView getTextViewlo() {
                return textViewlo;
            }

            //public TextView getTextViewPrice() {
            //    return textViewPrice;
            //}

            private final ImageView imageViewPicture;
            private final TextView textViewName;
            //private final TextView textViewPrice;
            private final TextView textViewData;
            private final TextView textViewla;
            private final TextView textViewlo;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                this.imageViewPicture= itemView.findViewById(R.id.image_view_book_cover);
                this.textViewName= itemView.findViewById(R.id.textview_item_name);
                this.textViewData = itemView.findViewById(R.id.textview_item_data);
                this.textViewla=itemView.findViewById(R.id.textview_item_la);
                this.textViewlo=itemView.findViewById(R.id.textview_item_lo);
                //this.textViewPrice=itemView.findViewById(R.id.textview_item_price);

                itemView.setOnCreateContextMenuListener(this);
            }

            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("具体操作");
                menu.add(0, 0, this.getAdapterPosition(), "修改" + this.getAdapterPosition());
                menu.add(0, 1, this.getAdapterPosition(), "删除" + this.getAdapterPosition());
            }
        }
    }
}